package com.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.question.constant.MessageConstant;
import com.question.constant.QuestionConstant;
import com.question.context.BaseContext;
import com.question.exception.QuestionNotFoundException;
import com.question.mapper.*;
import com.question.pojo.dto.UserFavoriteQuestionDTO;
import com.question.pojo.entity.*;
import com.question.pojo.vo.UserFavoriteQuestionVO;
import com.question.service.FavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionCategoriesMapper questionCategoriesMapper;
    @Autowired
    private QuestionChoicesMapper questionChoicesMapper;
    @Autowired
    private QuestionBlanksMapper questionBlanksMapper;
    @Autowired
    private QuestionStatisticsMapper questionStatisticsMapper;

    /**
     * 添加取消收藏
     * @param questionId
     */
    public void addOrCancel(Long questionId) {
        //判断该题是否存在
        Question question = questionMapper.selectByQuestionId(questionId.intValue());
        if (question == null) {
            throw new QuestionNotFoundException(MessageConstant.QUESTION_NOT_FOUND);
        }

        UserFavorites userFavorites = new UserFavorites();
        userFavorites.setQuestionId(questionId);
        userFavorites.setUserId(BaseContext.getCurrentId());

        // 判断用户是否收藏该题目
        Boolean isFavorite = favoriteMapper.findByUserIdAndQuestionId(userFavorites);

        if (isFavorite == null ) {
            // 添加收藏
            favoriteMapper.insert(userFavorites);
        } else {
            // 取消收藏
            favoriteMapper.deleteByUserIdAndQuestionId(userFavorites);
        }
    }

    /**
     * 用户收藏题目查询
     * @param favoriteQuestionDTO
     * @return
     */
    public List<UserFavoriteQuestionVO> getMyFavoriteQuestions(UserFavoriteQuestionDTO favoriteQuestionDTO) {
        //先查询出满足条件的题目
        List<UserFavoriteQuestionVO> favoriteQuestionList = favoriteMapper.listAllQuestions(BaseContext.getCurrentId(), favoriteQuestionDTO);

        for (UserFavoriteQuestionVO question : favoriteQuestionList) {

            //封装分类信息
            QuestionCategories questionCategories = questionCategoriesMapper.selectById(question.getCategoryId());
            question.setQuestionCategories(questionCategories);

            Integer questionId = question.getQuestionId();
            // 判断是选择题还是填空题
            if (question.getQuestionType().equals(QuestionConstant.CHOICE)){
                // 是选择题，获取相关选项
                QueryWrapper<QuestionChoices> wrapper = new QueryWrapper<>();
                wrapper.eq("question_id", questionId);
                List<QuestionChoices> questionChoices = questionChoicesMapper.selectList(wrapper);
                question.setQuestionChoicesList(questionChoices);

            }else {
                // 是填空题，获取相关填空信息
                QueryWrapper<QuestionBlanks> wrapper = new QueryWrapper<>();
                wrapper.eq("question_id",questionId);
                QuestionBlanks questionBlanks = questionBlanksMapper.selectOne(wrapper);
                question.setQuestionBlanks(questionBlanks);
            }

            // 统计题目回答次数和正确率
            QuestionStatistics questionStatistics = questionStatisticsMapper
                    .selectOne(new LambdaQueryWrapper<QuestionStatistics>()
                            .eq(QuestionStatistics::getQuestionId, questionId));

            Integer totalAttempts = questionStatistics.getTotalAttempts();
            Integer correctAttempts = questionStatistics.getCorrectAttempts();

            question.setAnswerTotal(totalAttempts);

            double correctRate = 0.0;
            if (totalAttempts > 0){
                correctRate = ((double)correctAttempts / totalAttempts) * 100;
            }
            // 保留两位小数
            question.setCorrectRate(String.format("%.2f%%", correctRate));
        }

        return favoriteQuestionList;
    }
}
